package com.my.framework.base.controller;

import com.google.common.collect.Lists;
import com.my.framework.SecurityConstants;
import com.my.framework.shiro.ShiroUser;
import com.my.xadmin.security.entity.Module;
import com.my.xadmin.security.entity.Permission;
import com.my.xadmin.security.service.ModuleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by mabo-pc on 2017-08-03.
 */
@Controller
@RequestMapping("/management/index")
public class IndexController {
	private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

	private static final String INDEX = "index";
	private static final String WELCOME="welcome";


	@Autowired
	private ModuleService moduleService;

	@RequiresUser
	@RequestMapping(value="/index", method= RequestMethod.GET)
	public String index(HttpServletRequest request) {
		Subject subject = SecurityUtils.getSubject();
		ShiroUser shiroUser = (ShiroUser)subject.getPrincipal();
		// 加入ipAddress
		shiroUser.setIpAddress(request.getRemoteAddr());

		Module menuModule = getMenuModule(subject);

		request.getSession().setAttribute(SecurityConstants.LOGIN_USER, shiroUser.getUser());
		request.setAttribute("menuModule", menuModule);

		return INDEX;
	}

	@RequestMapping(value="/welcome", method= RequestMethod.GET)
	public String welcome(HttpServletRequest request) {

		return WELCOME;
	}

	private Module getMenuModule(Subject subject) {
		Module rootModule = moduleService.getTree();

		check(rootModule, subject);
		return rootModule;
	}

	private void check(Module module, Subject subject) {
		List<Module> list1 = Lists.newArrayList();
		for (Module m1 : module.getChildren()) {
			// 只加入拥有view权限的Module
			if (subject.isPermitted(m1.getSn() + ":" + Permission.PERMISSION_READ)) {
				check(m1, subject);
				list1.add(m1);
			}
		}
		module.setChildren(list1);
	}
}
